package main

import (
	"context"
	"fmt"
	"github.com/kataras/iris/mvc"
	"iris-shop/app/backend/web/controllers"
	repositories "iris-shop/common/dao"
	dbMysql "iris-shop/common/db/mysql"
	"iris-shop/common/services"

	"github.com/kataras/iris"
)

func main() {

	//创建实例
	app := iris.New()
	//设置日志等级
	app.Logger().SetLevel("debug")
	//设置模板目录
	template := iris.HTML("./app/backend/web/views", ".html").Layout("shared/layout.html").Reload(true)
	app.RegisterView(template)
	//设置静态文件目录
	app.StaticWeb("/assets", "./app/backend/web/assets")
	//异常处理
	app.OnAnyErrorCode(func(ctx iris.Context) {
		ctx.ViewData("message",ctx.Values().GetStringDefault("message","页面出错了"))
		ctx.ViewLayout("")
		_ = ctx.View("shared/error.html")
	})
	//连接数据库
	db :=dbMysql.DBConn()

	ctx,cancel := context.WithCancel(context.Background())
	defer cancel()

	//5.注册控制器
	productRepository := repositories.NewProductManager("product",db)
	productSerivce :=services.NewProductService(productRepository)
	productParty := app.Party("/product")
	product := mvc.New(productParty)
	product.Register(ctx,productSerivce)
	product.Handle(new(controllers.ProductController))


	orderRepository := repositories.NewOrderMangerRepository("order",db)
	orderService := services.NewOrderService(orderRepository)
	orderParty := app.Party("/order")
	order := mvc.New(orderParty)
	order.Register(ctx,orderService)
	order.Handle(new(controllers.OrderController))

	//启动服务
	err := app.Run(
		iris.Addr("localhost:8081"),
		iris.WithoutServerError(iris.ErrServerClosed),
		iris.WithOptimizations,
		)
	if err != nil {
		panic("iris run error")
	}
	fmt.Println("hello")
}
